﻿using System;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using CivilRegistry.Common;
using CivilRegistry.ControlledModel;

namespace CivilRegistry
{
    public partial class RationCard : System.Web.UI.Page
    {
        Admin loggedInAdmin = null;
        Person loggedInPerson = null;
        bool isApproved;
        bool isDeactivated;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SessionHandler.CurrentSession.User == null)
            {
                Response.Redirect("~/Login.aspx?&redirect=RationCard.aspx");
            }

            SiteMaster masterPage = (SiteMaster)Page.Master;
            masterPage.SelectedMenu = "RationCard";

            lblStatus.Text = "";

            if (SessionHandler.CurrentSession.User is Admin)
            {
                this.loggedInAdmin = (Admin)SessionHandler.CurrentSession.User;
            }
            else if (SessionHandler.CurrentSession.User is Person)
            {
                this.loggedInPerson = (Person)SessionHandler.CurrentSession.User;
            }
            else
            {
                Response.Redirect("~/Default.aspx");
            }

            if (!Page.IsPostBack)
            {
                if (this.loggedInAdmin != null)
                {
                    pnlDisplay.Visible = false;
                    btnAddMembers.Visible = false;
                    btnRemoveMembers.Visible = false;
                    pnlAdmin.Visible = true;
                }
                else
                {
                    this.FillRationCardDisplayGrid(ControlledModel.RationCard.FindByPerson(this.loggedInPerson));
                    pnlAdmin.Visible = false;
                }
            }
        }

        private void FillRationCardGrid()
        {
            this.FillRationCardGrid("RationCardId", SortDirection.Ascending);
        }

        private void FillRationCardGrid(string columnName, SortDirection sortDirection)
        {
            int pageIndex = gvRationCard.PageIndex;
            if (pnlFilter.Visible)
            {
                gvRationCard.DataSource = (from rationCard in this.loggedInAdmin.GetRationCardsBy(cblFilter.Items[0].Selected, cblFilter.Items[1].Selected)
                                           select new
                                           {
                                               RationCardId = rationCard.RationCardId,
                                               FamilyName = rationCard.Family.FamilyName,
                                               FamilyOwnerName = rationCard.Family.Owner.FirstName,
                                               Members = rationCard.Family.Members.Count,
                                               IsApproved = rationCard.IsApproved
                                           }).OrderBy(columnName, sortDirection);
            }
            else
            {
                gvRationCard.DataSource = (from rationCard in this.loggedInAdmin.GetRationCardsForApproval()
                                           select new
                                           {
                                               RationCardId = rationCard.RationCardId,
                                               FamilyName = rationCard.Family.FamilyName,
                                               FamilyOwnerName = rationCard.Family.Owner.FirstName,
                                               Members = rationCard.Family.Members.Count,
                                               IsApproved = rationCard.IsApproved
                                           }).OrderBy(columnName, sortDirection);
            }
            gvRationCard.DataBind();
            gvRationCard.PageIndex = pageIndex;
        }

        protected void gvRationCard_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (SessionHandler.CurrentSession.SortDirection == SortDirection.Descending)
            {
                SessionHandler.CurrentSession.SortDirection = SortDirection.Ascending;
            }
            else
            {
                SessionHandler.CurrentSession.SortDirection = SortDirection.Descending;
            }

            this.FillRationCardGrid(e.SortExpression, SessionHandler.CurrentSession.SortDirection);
        }

        protected void gvRationCard_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvRationCard.PageIndex = e.NewPageIndex;
            this.FillRationCardGrid();
        }

        protected void gvRationCard_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
            {
                var hdnRationCardId = (HiddenField)gvRationCard.Rows[Convert.ToInt32(e.CommandArgument) - (gvRationCard.PageSize * gvRationCard.PageIndex)].FindControl("hdnRationCardId");

                this.FillRationCardDisplayGrid(ControlledModel.RationCard.FindById(Convert.ToInt32(hdnRationCardId.Value)));

                gvRationCard.Visible = false;
                pnlFilter.Visible = false;
                btnApply.Visible = false;
                btnAddMembers.Visible = false;
                btnRemoveMembers.Visible = false;
                pnlTools.Visible = false;
                pnlDisplay.Visible = true;
                pnlAdminActions.Visible = true;

                if (this.isApproved)
                {
                    btnApprove.Visible = false;
                    btnDeny.Visible = false;
                    btnDeactivate.Visible = true;
                    if (this.isDeactivated)
                    {
                        btnDeactivate.Text = "Re-Activate";
                    }
                    else
                    {
                        btnDeactivate.Text = "Deactivate";
                    }
                }
                else
                {
                    btnApprove.Visible = true;
                    btnDeny.Visible = true;
                    btnDeactivate.Visible = false;
                }
            }
        }

        protected void gvRationCard_RowEditing(object sender, GridViewEditEventArgs e)
        {
            e.Cancel = true;
        }

        private void FillRationCardDisplayGrid(ControlledModel.RationCard rationCard)
        {
            this.FillRationCardDisplayGrid(rationCard, "UserId", SortDirection.Ascending);
        }

        private void FillRationCardDisplayGrid(ControlledModel.RationCard rationCard, string columnName, SortDirection sortDirection)
        {
            if (rationCard != null)
            {
                int pageIndex = gvRationCard.PageIndex;
                gvRationCardDisplay.DataSource = (from familyMember in rationCard.Family.Members
                                                  select new
                                                      {
                                                          UserId = familyMember.UserId,
                                                          FirshtName = familyMember.FirstName,
                                                          MiddleName = familyMember.MiddleName,
                                                          LastName = familyMember.LastName,
                                                          Age = familyMember.Age
                                                      }).ToList();
                gvRationCardDisplay.DataBind();
                gvRationCard.PageIndex = pageIndex;

                this.isApproved = rationCard.IsApproved != null ? rationCard.IsApproved.Value : false;
                this.isDeactivated = rationCard.DeactivateReason == null ? false : true;
                this.hdnRationCardId.Value = rationCard.RationCardId.ToString();

                if (!File.Exists(rationCard.Family.Owner.GetPermanentAddressElectricalBillFilePath()))
                {
                    lbnViewElectricBillXerox.Visible = false;
                }
                else
                {
                    lbnViewElectricBillXerox.Visible = true;
                }
            }
            else
            {
                lblStatus.Text = "No RationCard found for you account. Please contact the relavant office for more information."
                    + " If you dont have the one, please apply for it.";
                pnlDisplay.Visible = false;
                btnApply.Visible = true;
            }
        }

        protected void gvRationCardDisplay_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (SessionHandler.CurrentSession.SortDirection == SortDirection.Descending)
            {
                SessionHandler.CurrentSession.SortDirection = SortDirection.Ascending;
            }
            else
            {
                SessionHandler.CurrentSession.SortDirection = SortDirection.Descending;
            }
            
            this.FillRationCardDisplayGrid(this.loggedInPerson.Family.RationCards.FirstOrDefault(), e.SortExpression, SessionHandler.CurrentSession.SortDirection);
        }

        protected void gvRationCardDisplay_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvRationCardDisplay.PageIndex = e.NewPageIndex;
            this.FillRationCardDisplayGrid(this.loggedInPerson.Family.RationCards.FirstOrDefault());
        }

        protected void cblFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.FillRationCardGrid();
        }

        protected void btnViewAll_Click(object sender, EventArgs e)
        {
            gvRationCard.Visible = true;
            pnlFilter.Visible = true;
            pnlTools.Visible = false;
            pnlDisplay.Visible = false;
            pnlAdminActions.Visible = false;

            this.FillRationCardGrid();
        }

        protected void btnViewRationCardRequest_Click(object sender, EventArgs e)
        {
            pnlTools.Visible = false;
            gvRationCard.Visible = true;
            pnlDisplay.Visible = false;
            pnlAdminActions.Visible = false;

            this.FillRationCardGrid();
        }

        protected void btnApply_Click(object sender, EventArgs e)
        {
            btnApply.Visible = false;
            pnlDisplay.Visible = false;
            pnlRationCardRequest.Visible = true;
            this.LoadEditAddressValues(this.loggedInPerson);
        }

        private void LoadEditAddressValues(ControlledModel.User user)
        {
            ((TextBox)ucPermanentAddress.FindControl("txtAddress")).Text = user.PermanentAddress.Address;
            ((TextBox)ucPermanentAddress.FindControl("txtPIN")).Text = user.PermanentAddress.PIN.ToString();
            ((DropDownList)ucPermanentAddress.FindControl("ddlStateName")).SelectedIndex = user.PermanentAddress.District.State.StateId;
            var ddlDistrictName = ((DropDownList)ucPermanentAddress.FindControl("ddlDistrictName"));
            ddlDistrictName.DataSource = District.FindAllByStateId(user.PermanentAddress.District.State.StateId);
            ddlDistrictName.DataBind();
            ddlDistrictName.SelectedValue = user.PermanentAddress.District.DistrictId.ToString();
            ((TextBox)ucPermanentAddress.FindControl("txtCity")).Text = user.PermanentAddress.City;

            if (user.PresentAddress != null)
            {
                ((TextBox)ucPresentAddress.FindControl("txtAddress")).Text = user.PresentAddress.Address;
                ((TextBox)ucPresentAddress.FindControl("txtPIN")).Text = user.PresentAddress.PIN.ToString();
                ((DropDownList)ucPresentAddress.FindControl("ddlStateName")).SelectedIndex = user.PresentAddress.District.State.StateId;
                ddlDistrictName = ((DropDownList)ucPresentAddress.FindControl("ddlDistrictName"));
                ddlDistrictName.DataSource = District.FindAllByStateId(user.PresentAddress.District.State.StateId);
                ddlDistrictName.DataBind();
                ddlDistrictName.SelectedValue = user.PresentAddress.District.DistrictId.ToString();
                ((TextBox)ucPresentAddress.FindControl("txtCity")).Text = user.PresentAddress.City;
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (((TextBox)ucPermanentAddress.FindControl("txtAddress")).Text != "")
            {
                PermanentAddress permanentAddress = this.loggedInPerson.PermanentAddress ?? new PermanentAddress();

                permanentAddress.Address = ((TextBox)ucPermanentAddress.FindControl("txtAddress")).Text;
                permanentAddress.PIN = (Convert.ToInt32(((TextBox)ucPermanentAddress.FindControl("txtPIN")).Text));
                permanentAddress.District = District.FindById(Convert.ToInt32(((DropDownList)ucPermanentAddress.FindControl("ddlDistrictName")).SelectedValue));
                permanentAddress.District.State = State.FindById(Convert.ToInt32(((DropDownList)ucPermanentAddress.FindControl("ddlStateName")).SelectedValue));
                permanentAddress.City = ((TextBox)ucPermanentAddress.FindControl("txtCity")).Text;

                this.loggedInPerson.PermanentAddress = permanentAddress;
            }

            if (((TextBox)ucPresentAddress.FindControl("txtAddress")).Text != "")
            {
                PresentAddress presentAddress = this.loggedInPerson.PresentAddress ?? new PresentAddress();

                presentAddress.Address = ((TextBox)ucPresentAddress.FindControl("txtAddress")).Text;
                presentAddress.PIN = (Convert.ToInt32(((TextBox)ucPresentAddress.FindControl("txtPIN")).Text));
                presentAddress.District = District.FindById(Convert.ToInt32(((DropDownList)ucPresentAddress.FindControl("ddlDistrictName")).SelectedValue));
                presentAddress.District.State = State.FindById(Convert.ToInt32(((DropDownList)ucPresentAddress.FindControl("ddlStateName")).SelectedValue));
                presentAddress.City = ((TextBox)ucPresentAddress.FindControl("txtCity")).Text;

                this.loggedInPerson.PresentAddress = presentAddress;
            }

            FileUpload electricityBillUploader = ((FileUpload)ucPermanentAddress.FindControl("FlupldElectricitybill"));
            if (electricityBillUploader.PostedFile.FileName != "")
            {
                if (electricityBillUploader.PostedFile.FileName.ToLowerInvariant().EndsWith(".pdf"))
                {
                    electricityBillUploader.SaveAs((this.loggedInPerson).GetPermanentAddressElectricalBillFilePath());
                }
                else
                {
                    lblStatus.Text = "Please upload a valid file. Note: The file should be in pdf format.";
                    return;
                }
            }

            electricityBillUploader = ((FileUpload)ucPresentAddress.FindControl("FlupldElectricitybill"));
            if (electricityBillUploader.PostedFile.FileName != "")
            {
                if (electricityBillUploader.PostedFile.FileName.ToLowerInvariant().EndsWith(".pdf"))
                {
                    electricityBillUploader.SaveAs((this.loggedInPerson).GetPresentAddressElectricalBillFilePath());
                }
                else
                {
                    lblStatus.Text = "Please upload a valid file. Note: The file should be in pdf format.";
                    return;
                }
            }

            ControlledModel.RationCard rationCard = new ControlledModel.RationCard();

            rationCard.Family = new Family() { FamilyName = txtFamilyName.Text, Owner = this.loggedInPerson };

            try
            {
                this.loggedInPerson.ApplyForRationCard(rationCard);
            }
            catch (ApplicationException ex)
            {
                lblStatus.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
                return;
            }

            lblStatus.Text = "Application sent successfully.";

            EmailHelper.SendApplicationRequestNotification("RationCard", this.loggedInPerson, ref lblStatus);
            SMSHelper.SendApplicationRequestNotification("RationCard", this.loggedInPerson, ref lblStatus);

            pnlRationCardRequest.Visible = false;
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            try
            {
                var rationCard = ControlledModel.RationCard.FindById(Convert.ToInt32(hdnRationCardId.Value));
                this.loggedInAdmin.ApproveRationCard(rationCard);
                lblStatus.Text = "The record is Approved successfully!";

                EmailHelper.SendApproveEmail("RationCard", rationCard.Family.Owner, ref lblStatus);
                SMSHelper.SendApproveSMS("RationCard", rationCard.Family.Owner, ref lblStatus);
            }
            catch (ApplicationException ex)
            {
                lblStatus.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
            }
            finally
            {
                pnlAdminActions.Visible = false;
            }
        }

        protected void btnDeactivate_Click(object sender, EventArgs e)
        {
            try
            {
                var rationCard = ControlledModel.RationCard.FindById(Convert.ToInt32(hdnRationCardId.Value));

                if (btnDeactivate.Text == "Re-Activate")
                {
                    this.loggedInAdmin.ReActivateRationCard(rationCard);
                    lblStatus.Text = "The record is Re-Activated successfully!";
                }
                else
                {
                    this.loggedInAdmin.DeactivateRationCard(rationCard, txtReason.Text);
                    lblStatus.Text = "The record is Deactivated successfully!";
                }


                EmailHelper.SendDeactivationEmail("RationCard", btnDeactivate.Text, rationCard.Family.Owner, txtReason.Text, ref lblStatus);
                SMSHelper.SendDeactivationSMS("RationCard", btnDeactivate.Text, rationCard.Family.Owner, ref lblStatus);
            }
            catch (ApplicationException ex)
            {
                lblStatus.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
            }
            finally
            {
                pnlAdminActions.Visible = false;
            }
        }

        protected void btnDeny_Click(object sender, EventArgs e)
        {
            try
            {
                var rationCard = ControlledModel.RationCard.FindById(Convert.ToInt32(hdnRationCardId.Value));
                this.loggedInAdmin.DenayRationCard(rationCard, txtReason.Text);
                lblStatus.Text = "The record is Denyed successfully!";

                EmailHelper.SendDenyNotificationEmail("RationCard", rationCard.Family.Owner, txtReason.Text, ref lblStatus); 
                SMSHelper.SendDenyNotificationSMS("RationCard", rationCard.Family.Owner, ref lblStatus);
            }
            catch (ApplicationException ex)
            {
                lblStatus.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
            }
            finally
            {
                pnlAdminActions.Visible = false;
            }
        }

        protected void btnAddMembers_Click(object sender, EventArgs e)
        {
            btnAddMembers.Visible = false;
            btnRemoveMembers.Visible = false;
            pnlAddmembers.Visible = true;
            pnlRemoveMembers.Visible = false;
        }

        protected void btnRemoveMembers_Click(object sender, EventArgs e)
        {
            ddlExistingMembers.DataSource = from member in this.loggedInPerson.Family.Members
                                            select new
                                            {
                                                UserId = member.UserId,
                                                FirstName = member.FirstName
                                            };
            ddlExistingMembers.DataBind();

            btnAddMembers.Visible = false;
            btnRemoveMembers.Visible = false;
            pnlRemoveMembers.Visible = true;
            pnlAddmembers.Visible = false;
        }

        protected void btnAddMember_Click(object sender, EventArgs e)
        {

        }

        protected void btnRemoveMember_Click(object sender, EventArgs e)
        {

        }

        protected void lbnViewElectricBillXerox_Click(object sender, EventArgs e)
        {
            string electricBillRelativePath = @"~\" + ControlledModel.RationCard.FindById(Convert.ToInt32(hdnRationCardId.Value))
               .Family.Owner.GetPermanentAddressElectricalBillFilePath()
               .Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
            Response.Redirect(electricBillRelativePath);
        }
    }
}